package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.cache.prefix.UserInfoKeyPrefix;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.member.service.IUserInfoService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Reference
    private IUserInfoService userInfoService;
    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @RequestMapping("/login")
    @ResponseBody
    public String testLogin(Long id){
        UserInfo userInfo = userInfoService.get(id);
        return "ok";
    }

    @RequestMapping("/checkPhone")
    @ResponseBody
    public Boolean checkPhone(String phone){
        return !userInfoService.checkPhone(phone);
    }

    @RequestMapping("/userRegist")
    @ResponseBody
    public AjaxResult userRegist(String phone, String nickname, String password, String rpassword, String verifyCode) {

         userInfoService.register(phone, nickname, password, rpassword, verifyCode);
         return new AjaxResult();

    }

    @RequestMapping("/userLogin")
    @ResponseBody
    public AjaxResult userLogin(HttpSession session,HttpServletResponse response, String username, String password){

        //检查用户是否存在，在第三方redis数据库中保存cookie，cookie{token【userInfo前缀+uuid随机生成的码】,value【userInfo】}，将查询出来的用户对象作为的value保存到redis中
        //这样的目的是为了在分布式系统中，当登录请求或者需要验证是否已经登录的时候，被分配到不同服务器的请求可以从redis缓存中获取userinfo；这里我们关键使用了Cookie
        String token = userInfoService.userLogin(username,password);

        //除了保存到redis中，还需要再把cookie返回给浏览器中，这样才完成了cookie的操作，返回的时候只返回userinfo前缀+uuid（token）
        CookieUtil.addCookie(response, UserInfoKeyPrefix.USER_INFO_COOKIE_NAME,token);

        //因为登录成功之后信息放在redis中，所以成功之后返回页面时，没有登录的用户数据，需要额外指定返回给页面上保存
        session.setAttribute("userInfo",userInfoRedisService.getUserInfoByToken(UserInfoKeyPrefix.USER_INFO_TOKEN,token));

        return new AjaxResult();

    }
}
